package org.dreamwork.jasmine2.misc;

import org.dreamwork.misc.Captcha;
import org.dreamwork.misc.CaptchaType;

import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: seth.yang
 * Date: 13-12-6
 * Time: 下午2:52
 */
public class CaptchaManager {
    private static final String CAPTCHA_KEY = "org.dreamwork.misc.captcha";

    private static class CaptchaHolder {
        private String value;
        private long timestamp;

        private CaptchaHolder () {
        }

        public String getValue () {
            return value;
        }

        public void setValue (String value) {
            this.value = value;
        }

        public long getTimestamp () {
            return timestamp;
        }

        public void setTimestamp (long timestamp) {
            this.timestamp = timestamp;
        }
    }

    public static void save (Captcha captcha, HttpSession session) {
        CaptchaType type = captcha.getType ();
        CaptchaHolder holder = new CaptchaHolder ();
        holder.setTimestamp (System.currentTimeMillis ());
        if (type == CaptchaType.Formula) {
            holder.setValue (String.valueOf (captcha.getFormulaResult ()));
        } else {
            holder.setValue (captcha.getContent ());
        }
        session.setAttribute (CAPTCHA_KEY, holder);
    }

    public static CaptchaCheckResult check (String value, HttpSession session, int timeout, boolean ignoreCase) {
        CaptchaHolder holder = (CaptchaHolder) session.getAttribute (CAPTCHA_KEY);
        if (holder == null)
            return CaptchaCheckResult.Not_Exit;

        if (timeout > 0) {
            long delta = System.currentTimeMillis () - holder.timestamp;
            if (delta / 1000 > timeout)
                return CaptchaCheckResult.Timed_Out;
        }

        if (ignoreCase) {
            if (!value.equalsIgnoreCase (holder.value))
                return CaptchaCheckResult.Not_Match;
        } else if (!value.equals (holder.value)) {
            return CaptchaCheckResult.Not_Match;
        }

        session.removeAttribute (CAPTCHA_KEY);
        return CaptchaCheckResult.Success;
    }
}